#!/usr/bin/env bash

# DESCRIPTION
#     This script corrects most (but not all) model rendering issues on macOS
#     (Metal API, MoltenVK) by computing skinned meshes by the CPU instead of GPU.
#
# EXIT STATUS
#     0      : The patch was applied successfully or is not needed by your system.
#     other  : Patch failure. See stdout or stderr output for details.
#
# AUTHOR
#     3Shain (2023)


if ! [[ $(uname) == "Darwin" ]]; then
	echo "You do not need this patch if you are not on macOS."
	exit 0
fi

DIR=$(dirname "${BASH_SOURCE[0]}")
DATADIR=$(find . -maxdepth 1 -type d -name "*_Data")
GGM="$DATADIR/globalgamemanagers"
PATTERN="67616d657300000001"

match=$(xxd -p -c 100000000 < "$GGM" | grep -o "$PATTERN")
if [ -z "$match" ]; then
	echo "[ERROR] Incompatible file or the patch is already applied."
	exit 1
fi

echo "--- Patching globalgamemanagers"

mv -f "$GGM" "$GGM.bak"
# Universal for both CN and OS game builds
xxd -p -c 100000000 < "$GGM.bak" | sed "s/${PATTERN}/67616d657300000000/" | xxd -r -p > "$GGM"

# Done!
echo "==> Patch applied! Enjoy the game."
echo
echo "[NOTICE]  Please refrain from sharing this project in public so"
echo "		  that there can be Linux patches in the future. Thank you."

exit 0
